package com.atguigu.windowFunction;

import com.atguigu.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

/**
 * Created by RUI on 2021/6/17 16:25
 *
 * 指定时间范围内网站独立访客数（UV）的 实时统计每小时
 */
public class High_prj_UV {

    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);

        env.readTextFile("input/UserBehavior.csv")
                .map(value -> {
                    String[] split = value.split(",");
                    return new UserBehavior(Long.valueOf(split[0]), Long.valueOf(split[1]), Integer.valueOf(split[2]), split[3], Long.parseLong(split[4])*1000);
                })
                .filter(ub->"pv".equals(ub.getBehavior()))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.getTimestamp();
                                    }
                                })
                )
                .keyBy(UserBehavior::getBehavior)
                .window(TumblingEventTimeWindows.of(Time.hours(1)))
                .process(new ProcessWindowFunction<UserBehavior, String, String, TimeWindow>() {

                    private MapState<Long, Object> userIdState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        userIdState = getRuntimeContext().getMapState(new MapStateDescriptor<Long, Object>("userIdState", Long.class, Object.class));
                    }

                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<UserBehavior> elements,
                                        Collector<String> out) throws Exception {

                        userIdState.clear();
                        long count = 0L;

                        for (UserBehavior element : elements) {
                            userIdState.put(element.getUserId(),null);
                        }

                        for (Long aLong : userIdState.keys()) {
                            count++;
                        }

                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH：mm:ss");

                        String msg = "窗口:"+key+": [" + df.format(new Date(ctx.window().getStart())) + "," + df.format(new Date(ctx.window().getEnd())) + "), count=" + count;
                        out.collect(msg);

                    }
                })
                .print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
